#include "Key.h"
#include "TIMER\timer.h"

   sbit Led4 =P3^4;
   sbit Led5 =P3^5;
   sbit Led6 =P3^6;
   sbit Led7 =P3^7;
extern unsigned char key;
unsigned char 	preKey;
unsigned int 	isValidKey;
unsigned int 	timeoutKey=0;
unsigned char dataKey[4]={0xF7,0xFB,0xFD,0xFE};

unsigned char keyInput() { 
		/*********************
	3		0	|	1		2		3		A (13)		
	2		1	|	4		5		6		B (16)
	1		2	|	7		8		9		C (19)
  P3.0		x=3	|	E(10)	0		F(12)	D (22)
			  --------------------
					led7	Led6	led5	Led4
		**********************/
	unsigned char keyValue=_NULL_;
	unsigned char x,y;   
	for(x=0; x<4;x++){ 
		P3=dataKey[x];
		for(y=0;y<4;y++){ 
			if(Led5==0) 
						keyValue=3*x+3;
			if(Led6==0)	 
				if(x!=3)	keyValue=3*x+2;
				else	keyValue=0;					
			if(Led7==0)
					keyValue=3*x+1;		
			if(Led4==0)
						keyValue=3*x+13;;	 	
		} 		
		


	} 
	return(keyValue);  
}
void scanKey(){

	unsigned char keyTemp=keyInput();
	isValidKey=checkValidKey(keyTemp);
		if(!isValidKey){
			key=_NULL_;	
		} else {
			key=keyTemp;  
		}
}
unsigned int checkValidKey(	unsigned char keyCheck){
 	 if (timeoutKey>0)
	 	 timeoutKey--; 

	 if (keyCheck==preKey){
	 	if (timeoutKey!=0)
			return 0;
		else{
			preKey=keyCheck; 
			timeoutKey=50;
			return 1;
		}
	 } else {
	 	  	if (keyCheck!=_NULL_){
		  		preKey=keyCheck;
				return 1;
			}else return 0;
	 }
	 
}
